package http.secure.common.config;

import http.secure.common.constant.SecureApiProperties;
import http.secure.common.constant.SecureProperties;
import http.secure.common.filter.ExchangeHandler;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * 密钥交换动态控制器
 */
@Configuration
@RequiredArgsConstructor
public class SecureControllerRegistrar {
    private final RequestMappingHandlerMapping handlerMapping;
    private final ExchangeHandler exchangeHandler;
    private final SecureProperties properties;

    /**
     * 动态注册控制器方法
     */
    @Bean
    CommandLineRunner registerSecureController() {
        return args -> {
            SecureApiProperties api = properties.getApi();
            registerMethodAPI(api.getKeyExchangePath(), "exchange");
            registerMethodAPI(api.getKeyRotationPath(), "rotation");
        };
    }

    private void registerMethodAPI(String api, String methodName) throws NoSuchMethodException {
        Method method = Arrays.stream(ExchangeHandler.class.getMethods())
                .filter(e -> e.getName().equals(methodName))
                .findFirst()
                .orElseThrow(NoSuchMethodException::new);
        RequestMappingInfo.Builder builder1 = RequestMappingInfo
                .paths(api)
                .methods(RequestMethod.POST);
        handlerMapping.registerMapping(builder1.build(), exchangeHandler, method);
    }
}